﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Bainx.Extend
{
    /// <summary>
    /// 跨线程调用（WinForm）
    /// </summary>
    public static class ControlExtensions
    {
        /// <summary>
        /// 跨线程调用
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="doit"></param>
        public static void InvokeIfNeeded(this Control ctl, Action doit)
        {
            if (ctl.InvokeRequired)
                ctl.Invoke(doit);
            else
                doit();
        }
        /// <summary>
        /// 跨线程调用
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ctl"></param>
        /// <param name="doit"></param>
        /// <param name="args"></param>
        public static void InvokeIfNeeded<T>(this Control ctl, Action<T> doit, T args)
        {
            if (ctl.InvokeRequired)
                ctl.Invoke(doit, args);
            else
                doit(args);
        }
    }
    //在多线程环境中使用InvokeIfNeeded能够很大程度上简化事件处理程序的代码。
    //private void OnTick(object sender, EventArgs e)
    //{
    //this.InvokeIfNeeded(() => toolStripStatusLabel1.Text =
    //DateTime.Now.ToLongTimeString());
    //}
}
